import { sendCodeApi, loginApi, openidAPI, getUserApi, setUserApi,
 userTagApi,localtLogin, userAccountApi,getOtherApi,getPayerDy,
 getPayerScen,getUserClock,userLeisurelyList, faultAccount
 } from "../apis/index.js";
import { loadUserInfo } from '@/config/cache';
import mTool from '../common/tools.js'
import QQMapWX from '../common/qqmap-wx-jssdk.min.js'

const loginSMS = 'abggheh;;;;rjfjaaf..fljfflf.__.'

let qqmapsdk = new QQMapWX({
  key: 'BM6BZ-FEK3D-C5M4K-HDUXO-LDEI2-3IBJY'
});

class User{
	
	username
	bean = 0				// 豆子
	charm = 0				// 网易号
	diamond = 0				// 钻石
	fansNum = 0				// 粉丝数
	integral = 0			// 积分
	attentNum = 0			// 关注
	balanceaccount = 0		// 余额
	longitude = 108.981883
	latitude =  34.23973
	city =  '西安市'
	faultAccount = null
	
	userDataList =  [
		{
			key: 'attentNum',
			name: '关注',
			path: 'myattent'
		},{
			key: 'fansNum',
			name: '粉丝',
			path: 'myfans'
		},{
			key: 'integral',
			name: '积分',
			path: ''
		},
	]
		
	//代理模式
	constructor() {
		
		// 已经实例化直接返回实例对象
		if (typeof User.instance === 'object') {
		    return User.instance;
		}
		
		this.username = this._getLocalUserName();
		
		// 缓存
		User.instance = this;
		return this;
		
	}
	
    static async sendCode(telnumber) {
		let fronttime = mTool.getCurTime()
        await sendCodeApi({
			telnumber,
			fronttime
		})
    }
	
    static login(telnumber, smsverify) {
		let fronttime = mTool.getCurTime()
        return loginApi({
			telnumber,
			smsverify,
			loginType: '104'
		})
    }
	
	
	
	async localtLogin() {
		let latitude = this.latitude || 34.161716;
		let longitude = this.longitude || 108.985606;
		return localtLogin({
			lng: longitude,
			lat: latitude,
		})
	}
	
	static async reLogin(loginMobile) {
		return User.login(loginMobile, loginSMS)
	}
	
	async getTokenFromServer() {
		
		let loginOpenid = uni.getStorageSync("loginOpenid");
		if(loginOpenid) return loginOpenid
		let [, {provider}] = await uni.getProvider({service: 'oauth'})
		if(provider.indexOf('weixin')<0) {
			throw new Error('获取服务供应商失败')
		}
	    let [, wxCode] = await uni.login({provider: 'weixin'})
		let wxLogin = await openidAPI({
			code: wxCode.code
		})
		uni.setStorageSync("loginOpenid", wxLogin.openid);
		
		return wxLogin.openid
	}
	
	_getLocalUserName() {
		const token = uni.getStorageSync('Token');
		if(token && token.username){
			return token.username
		}
	    return ''
	}
	
	updateUserInfo() {
		let username = this.username
        return getUserApi({
			userid: username,
			othername: username,
			username
		})
    }
	
	getOtherInfo(othername) {
		let username = this.username
		return getUserApi({
			userid: username,
			othername,
			username
		})
	}
	
	updateUserData(userData) {
		if(!userData) return
		this.fansNum = userData.fansNum
		this.attentNum = userData.attentNum
		this.username = userData.username
		if(userData.netaccount) {
			uni.setStorageSync("loginIM", {
				netaccount: userData.netaccount,
				nettoken: userData.nettoken
			});
		}
	}
	
	changeUserInfo(data) {
		let username = this.username
		return setUserApi({
			username,
			...data
		})
	}
	
	
	clearUserInfo() {
		this.username = ''
		this.charm = 0
		this.fansNum = 0
		this.integral = 0
		this.attentNum= 0
	}
	
	
	getUserTag() {
		let username = this.username
		return userTagApi({
			username
		})
		
	}
	
	
	async getUserAccount() {
		let userAccount = await userAccountApi()
		this.bean = userAccount.bean
		this.charm = userAccount.charm
		this.diamond = userAccount.diamond
		this.integral = userAccount.integral
		this.balanceaccount = userAccount.balanceaccount
	}
	
	async getFaultAccount(flag) {
		if(flag || !this.faultAccount) {
			this.faultAccount = await faultAccount()
		}
		return this.faultAccount
	}
	
	
	async getPlayerInfo(othername) {
		let username = this.username
		return getOtherApi({
			othername,
			username
		})
	}
	
	async getPayerDy(pagenum, othername) {
		return getPayerDy({
			pagenum,
			username: othername
		})
	}
	
	async getPayerScen(pagenum, othername) {
		return getPayerScen({
			othername,
			pagenum
		})
	}
	
	async getUserClock(pagenum, othername) {
		return getUserClock({
			othername,
			pagenum
		})
	}
	
	async getIdleList(pagenum, username) {
		return userLeisurelyList({
			pagenum,
			username
		})
	}


	showConfirm() {
	    console.log('需要弹窗授权');
		uni.showModal({
		    title: '是否授权当前位置',
		    content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
		    success: (res) => {
		        if (res.cancel) {
		            uni.showToast({
		                title: '定位失败',
		                icon: 'none',
		                duration: 1000
		            })
		        } else if (res.confirm) {
		           this.openSetting()
		        }
		    }
		})
	}
	
	hideConfirm() {
	    console.log('关闭弹窗授权');
	}
	
	
	async getLocation() {
		// #ifdef APP-PLUS
		let status = await this.checkPermission();
		if (status !== 1) {
			return;
		}
		// #endif
		// #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
		let status = await this.getSetting();
		if (status === 2) {
			this.showConfirm()
			return;
		}
		// #endif
	
		this.doGetLocation();
	}
	
	doGetLocation() {
	    uni.getLocation({
	        success: (res) => {
	            this.longitude = res.longitude;
	            this.latitude = res.latitude;
				let self = this
				qqmapsdk.reverseGeocoder({
					location:{
						latitude: res.latitude,
						longitude: res.longitude
					},
					success(map){
						// console.log("map",map.result.address_component.city);
						self.city = map.result.address_component.city
					}
				})
	        },
	        fail: (err) => {
	            // #ifdef MP-BAIDU
	            if (err.errCode === 202 || err.errCode === 10003) { 
					// 202模拟器 10003真机 user deny
	                this.showConfirm()
	            }
	            // #endif
	            // #ifndef MP-BAIDU
	            if (err.errMsg.indexOf("auth den") >= 0) {
	                uni.showToast({
	                    title: "访问位置被拒绝",
						icon: 'none'
	                })
	            } else {
	                uni.showToast({
	                    title: err.errMsg
	                })
	            }
	            // #endif
	        }
	    })
	}
	
	getSetting() {
	    return new Promise((resolve, reject) => {
	        uni.getSetting({
	            success: (res) => {
	                if (res.authSetting['scope.userLocation'] === undefined) {
	                    resolve(0);
	                    return;
	                }
	                if (res.authSetting['scope.userLocation']) {
	                    resolve(1);
	                } else {
	                    resolve(2);
	                }
	            }
	        });
	    });
	}
	
	
	openSetting() {
	    this.hideConfirm();
	    uni.openSetting({
	        success: (res) => {
	            if (res.authSetting && res.authSetting['scope.userLocation']) {
	                this.doGetLocation();
	            }
	        },
	        fail: (err) => {}
	    })
	}
	
	async checkPermission() {
	    let status = permision.isIOS ? await permision.requestIOS('location') :
	        await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');
	
	    if (status === null || status === 1) {
	        status = 1;
	    } else if (status === 2) {
	        uni.showModal({
	            content: "系统定位已关闭",
	            confirmText: "确定",
	            showCancel: false,
	            success: function(res) {
	            }
	        })
	    } else if (status.code) {
	        uni.showModal({
	            content: status.message
	        })
	    } else {
	        uni.showModal({
	            content: "需要定位权限",
	            confirmText: "设置",
	            success: function(res) {
	                if (res.confirm) {
	                    permision.gotoAppSetting();
	                }
	            }
	        })
	    }
	
	    return status;
	}
	
}

export {
    User
}